<template>
  <div class="all">
    <div class="top">
      <el-row>
        <el-form ref="form" inline label-position="left">
          <el-col :span="3">
            <el-form-item :label="$t('app.asset.equipment.coding')">
              <el-input v-model="query.coding" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item :label="$t('app.asset.equipment.name')">
              <el-input v-model="query.name" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item :label="$t('app.status')">
              <SelfSelect v-model="query.status" :show-list="eqStatus" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="设备类别">
              <SelfSelect v-model="query.weight" :show-list="eqWeight" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="型号">
              <el-input v-model="query.spec" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="品牌">
              <el-input v-model="query.brand" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="环保设备">
              <SelfSelect v-model="query.hb" :show-list="YN" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="特种设备">
              <SelfSelect v-model="query.special" :show-list="YN" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="供应商">
              <Selects v-model="query.provider_id" action="providerList" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="制造商">
              <Selects v-model="query.manufacturer_id" action="providerList" :query="{ is_manufacturer: 1 }" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item>
              <el-button style="margin-top: 38%" icon="el-icon-search" type="primary" @keyup.enter.native="index" @click="index">查找</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <el-row class="btns">
        <el-button v-if="roles.includes('AssetJigEdit')" type="primary" icon="el-icon-circle-plus-outline" @click="handleAdd">
          {{ $t('button.create') }}</el-button>
        <el-button type="primary" icon="el-icon-printer" @click="exportDialog">{{ $t('button.export') }}</el-button>
        <div class="buttonBox">
          <el-upload v-if="roles.includes('AssetJigEdit')" :show-file-list="false" action="" :before-upload="file => workbook(file)">
            <el-button type="primary" icon="el-icon-edit" size="mini">{{ $t('button.import') }}</el-button>
          </el-upload>
        </div>
        <el-button v-if="roles.includes('AssetJigEdit')" type="danger" icon="el-icon-delete" @click="delBtn">{{ $t('button.delete') }}</el-button>
        <el-button v-if="roles.includes('AssetJigEdit')" type="primary" icon="el-icon-download" @click="downloadExcel">{{ $t('button.template') }}</el-button>
        <el-button type="primary" icon="el-icon-refresh" @click="refresh">{{ $t('button.refresh') }}</el-button>
      </el-row>
      <span class="total">{{ $t('app.count') }}：{{ total }}</span>
    </div>
    <div class="main">
      <div class="left">
        <el-tabs type="border-card" stretch style=" overflow: auto;height: 60vh" @tab-click="handleClick">
          <el-tab-pane :label="$t('app.asset.equipment.positionTree')">
            <el-input v-model="filterPositionText" size="small" style="margin-bottom: 10px" placeholder="请输入关键字进行过滤" />
            <el-tree ref="tree" :data="positionTree" accordion :props="positionProps" :expand-on-click-node="false" :filter-node-method="filterNode" @node-click="positionClick" />
          </el-tab-pane>
          <el-tab-pane :label="$t('app.asset.equipment.categoryTree')">
            <el-input v-model="filterCategoryText" size="small" style="margin-bottom: 10px" placeholder="请输入关键字进行过滤" />
            <el-tree ref="tree" :data="categoryTree" accordion :props="categoryProps" :expand-on-click-node="false" :filter-node-method="filterNode" @node-click="categoryClick" />
          </el-tab-pane>
        </el-tabs>
      </div>
      <div class="right">
        <el-table ref="multipleTable" :key="tableKey" v-loading="loading" border tooltip-effect="dark" width="100%" stripe height="60vh" :data="dataList" @selection-change="handleSelectionChange">
          <el-table-column :label="$t('app.Num')" type="index" align="center" width="50" />
          <el-table-column type="selection" align="center" width="55" />
          <el-table-column prop="coding" :label="$t('app.asset.equipment.coding')" align="center" width="180" show-overflow-tooltip  />
          <el-table-column prop="name" :label="$t('app.asset.equipment.name')" align="center" width="240" show-overflow-tooltip  />
          <el-table-column prop="spec" :label="$t('app.asset.equipment.spec')" align="center" width="140" show-overflow-tooltip  />
          <el-table-column prop="status" :label="$t('app.status')" align="center">
            <template scope="{row}">
              <div v-html="row.status_table" />
            </template>
          </el-table-column>
          <el-table-column prop="serialize" label="出厂编号" align="center" width="150" show-overflow-tooltip />
          <el-table-column prop="brand" :label="$t('app.asset.equipment.brand')" align="center" width="160" show-overflow-tooltip />
          <el-table-column prop="guarantee" :label="$t('app.asset.equipment.guarantee')" align="center" show-overflow-tooltip />
          <el-table-column prop="process" :label="$t('app.asset.equipment.process')" align="center" width="180" show-overflow-tooltip />
          <el-table-column prop="weight" label="设备类别" align="center" show-overflow-tooltip />
          <el-table-column prop="fun" :label="$t('app.asset.equipment.fun')" align="center" show-overflow-tooltip />
          <el-table-column prop="manufacture_date" :label="$t('app.asset.equipment.manufacture')" align="center" width="160" show-overflow-tooltip />
          <el-table-column prop="purchase_date" :label="$t('app.asset.equipment.purchase')" align="center" width="160" show-overflow-tooltip />
          <el-table-column prop="price" :label="$t('app.asset.equipment.price')" align="center" show-overflow-tooltip />
          <el-table-column prop="original_value" label="原值" align="center" show-overflow-tooltip />
          <el-table-column prop="hb" :label="$t('app.asset.equipment.hb')" align="center" />
          <el-table-column prop="special" :label="$t('app.asset.equipment.special')" align="center" show-overflow-tooltip />
          <el-table-column prop="cost" :label="$t('app.asset.equipment.cost')" align="center" show-overflow-tooltip />
          <el-table-column prop="parent" :label="$t('app.asset.equipment.parent')" align="center" width="150" show-overflow-toolti  />
          <el-table-column prop="category" :label="$t('app.asset.equipment.category')" align="center" width="200" show-overflow-tooltip />
          <el-table-column prop="first_category" :label="$t('app.asset.equipment.firstCategory')" align="center" width="200" show-overflow-tooltip />
          <el-table-column prop="workshop" :label="$t('app.asset.equipment.workshop')" align="center" width="180" show-overflow-tooltip />
          <el-table-column prop="process" :label="$t('app.asset.equipment.process')" align="center" width="180" show-overflow-tooltip />
          <el-table-column prop="used_group" :label="$t('app.asset.equipment.usedGroup')" align="center" width="200" show-overflow-tooltip />
          <el-table-column prop="provider" :label="$t('app.asset.equipment.provider')" align="center" width="200" show-overflow-tooltip />
          <el-table-column prop="manufacturer" :label="$t('app.asset.equipment.manufacturer')" align="center" width="200" show-overflow-tooltip />
          <el-table-column prop="motor" :label="$t('app.asset.equipment.motor')" align="center" show-overflow-tooltip />
          <el-table-column prop="power" :label="$t('app.asset.equipment.power')" align="center" show-overflow-tooltip />
          <el-table-column prop="admin_list" label="负责人" align="center" width="300" />
          <el-table-column v-if="roles.includes('AssetEquipmentDelete' || 'AssetEquipmentDetail')" :label="$t('app.handle')" fixed="right" width="180" align="center">
            <template scope="{row}">
              <el-button v-if="roles.includes('AssetJigDetail')" type="primary" @click="goDetail(row.id)">{{ $t('button.edit') }}</el-button>
              <el-button v-if="roles.includes('AssetJigEdit')" type="danger" @click="handleDel(row.id)">{{ $t('button.delete') }}</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination class="page" align="center" background :page-size="query.limit" layout="total,prev,pager,next,jumper" :total="total" :current-page.sync="query.page" @current-change="index" @size-change="index" />
      </div>
    </div>
    <el-dialog v-loading="isLoading" title="请选择导出字段" :visible.sync="excelDialog" width="60%" :element-loading-text="loadingExcel" element-loading-spinner="el-icon-loading">
      <div>
        <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
        <div style="margin: 15px 0;" />
        <el-checkbox-group v-model="needExport" @change="handleCheckedCitiesChange">
          <el-checkbox v-for="title in tableHead" :key="title" class="checkStyle" :label="title" />
        </el-checkbox-group>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="excelDialog = false">取 消</el-button>
        <el-button type="primary" @click="exportExcel">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Selects from '@/components/select-search'
import SelfSelect from '@/components/select-o'
import API from '@/api/asset/equipment'
import { eqTables } from '@/utils/Table'
import XLSX from 'xlsx'
import { mapGetters } from 'vuex'
import { eqStatus, eqType, eqWeight, YN } from '@/utils/option'
const tableOptions = ['设备编号', '设备名称', '车间', '生产线', '工位', '存放位置', '一级分类', '二级分类', '上级设备', '成本中心', '供应商', '制造商', '使用岗位', '品牌', '型号', '设备类别', '生产日期', '购置日期', '质保期', '购置价格', '原值', '功率', '电机数', '关键性', '资产性质', '状态', '环保设备', '特种设备', '排序']
export default {
  inject: ['goUrl', 'reload'],
  components: {
    SelfSelect,
    Selects
  },
  data() {
    return {
      positionTree: [],
      categoryTree: [],
      dataList: [],
      total: 0,
      loading: true,
      isLoading: false,
      loadingExcel: '正在导出...',
      query: {
        limit: 15,
        page: 1,
        type: 2
      },
      YN,
      filterCategoryText: '',
      filterPositionText: '',
      eqStatus,
      eqType,
      eqWeight,
      categoryProps: {
        children: 'children',
        label: 'name'
      },
      positionProps: {
        children: 'children',
        label: 'name'
      },
      tableKey: '',
      fileList: [],
      multipleSelection: [],
      excelDialog: false,
      exportList: [],
      eqTables,
      needExport: ['设备编号', '设备名称', '车间', '生产线', '工位', '存放位置', '一级分类', '二级分类', '上级设备', '成本中心', '供应商', '制造商', '使用岗位', '品牌', '型号', '设备类别', '生产日期', '购置日期', '质保期', '购置价格', '原值', '功率', '电机数', '关键性', '资产性质', '状态', '环保设备', '特种设备', '排序'],
      isIndeterminate: true,
      tableHead: tableOptions,
      checkAll: true
    }
  },
  computed: {
    ...mapGetters(['roles']),
    pages() {
      return this.total / 150 + 1
    }
  },
  watch: {
    filterPositionText(val) {
      this.$refs.tree.filter(val)
    },
    filterCategoryText(val) {
      this.$refs.newTree.filter(val)
    }
  },
  created() {
    API.tree().then(res => {
      this.categoryTree = res.data
    })
    API.newTree().then(res => {
      this.positionTree = res.data
    })
    const query = JSON.parse(sessionStorage.getItem('query'))
    if (query) {
      this.query = query
      sessionStorage.removeItem('query')
    }
    this.index()
    window.addEventListener('keydown', this.handKeyCode, true)
  },
  methods: {
    index() {
      console.log(this.query)
      this.loading = true
      API.getList(this.query).then(res => {
        this.dataList = res.data.data
        this.total = res.data.total
      }).finally(() => {
        this.loading = false
      })
    },
    handKeyCode(e) {
      if (e.keyCode === 13 || e.keyCode === 32) {
        this.index()
      }
    },
    goDetail(id) {
      this.setStorage()
      const url = `/jig/edit/${id}`
      this.goUrl(url)
    },
    refresh() {
      this.reload()
    },
    handleAdd() {
      this.setStorage()
      this.goUrl('/jig/add')
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleClick(tab, event) {
      console.log(tab)
    },
    handleDel(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        API.delete(id).then(res => {
          if (res.data.error_code !== 1) {
            this.$message.error(res.data.message)
          } else {
            this.$message.success('删除成功')
            this.setStorage()
            this.index()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    categoryClick(v) {
      this.query.category_id = v.id
      this.index()
    },
    positionClick(v) {
      this.query.position_id = v.id
      this.index()
    },
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    delBtn() {
      if (this.multipleSelection && this.multipleSelection.length > 0) {
        const idArray = []
        this.multipleSelection.forEach(item => {
          idArray.push(item.id)
        })
        const id = idArray.join(',')
        this.handleDel(id)
      } else {
        this.$message('请先选择，然后再删除')
      }
    },
    workbook(file) {
      this.loading = true
      const reader = new FileReader()
      const self = this
      reader.onload = function(e) {
        let outData = []
        const data = e.target.result
        const workbook = XLSX.read(data, { type: 'binary' })
        const sheetNames = workbook.SheetNames
        sheetNames.forEach(() => {
          outData = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]])
        })
        const postData = {}
        postData.outData = outData
        postData.type = 2
        API.excel(postData).then(response => {
          if (response.data.error_code === 1) {
            self.$message.success(`恭喜你，操作成功`)
            self.loading = false
            self.index()
          } else {
            self.$message.error(response.data.message)
            self.loading = false
            self.index()
          }
        }).finally(() => {
          self.loading = false
        })
      }
      reader.readAsBinaryString(file)
      return false
    },
    exportDialog() {
      this.excelDialog = true
    },
    downloadExcel() {
      const a = document.createElement('a')
      a.href = 'https://d.ubeiyun.com/xls/设备台账.xlsx'
      a.download = '设备台账.xlsx'
      a.style.display = 'none'
      document.body.appendChild(a)
      a.click()
      a.remove()
    },
    handleCheckAllChange(val) {
      this.needExport = val ? tableOptions : []
      this.isIndeterminate = false
    },
    handleCheckedCitiesChange(value) {
      const checkedCount = value.length
      this.checkAll = checkedCount === this.tableHead.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.tableHead.length
    },
    toExcel() {
      const exportData = []
      const exportTitle = []
      const titleObj = this.eqTables
      exportData.push(this.needExport)
      for (const keys of this.needExport) {
        exportTitle.push(Object.keys(titleObj).find(key => titleObj[key] === keys))
      }
      this.exportList.forEach(item => {
        const arr = []
        for (const key of exportTitle) {
          arr.push(item[key])
        }
        exportData.push(arr)
      })
      const ws = XLSX.utils.aoa_to_sheet(exportData)
      const wb = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
      /* save to file */
      this.loading = false
      XLSX.writeFile(wb, '设备台账.xlsx')
      this.isLoading = false
    },
    async getExcel(condition) {
      this.exportList = []
      const res = await API.getList(condition)
      const exportList = res.data.data
      const total = res.data.total
      this.exportList.push(...exportList)
      console.log(this.exportList.length, total)
      if (this.exportList.length === total) {
        this.isLoading = false
        this.toExcel()
      }
    },
    allExcel() {
      this.isLoading = true
      const arr = Object.keys(this.query)
      const len = arr.length
      console.log(len)
      if (len > 5 || this.query.manufacturer_id || this.query.provider_id) {
        console.log('带条件的导出')
        const condition = this.query
        condition.limit = this.total
        condition.page = 1
        this.getExcel(condition)
      } else {
        console.log('不带条件')
        for (let i = 1; i <= this.pages; i++) {
          const condition = {
            limit: 150,
            page: i,
            type: 2
          }
          this.getExcel(condition)
        }
      }
    },
    exportExcel() {
      if (this.multipleSelection && this.multipleSelection.length > 0) {
        this.exportList = this.multipleSelection
        this.toExcel()
      } else {
        this.allExcel()
      }
    },
    setStorage() {
      sessionStorage.setItem('query', JSON.stringify(this.query))
    }
  }
}
</script>
<style>
  .buttonBox{
    padding: 0 6px 0;
  }
</style>
